//
//  IssueViewController.m
//  yunyan
//
//  Created by haichuang on 2018/4/4.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "IssueViewController.h"
#import "BRPlaceholderTextView.h"
#import "ReleaseResultsView.h"
#import "MyPictureViewController.h"


#define kMaxTextCount 1000
@interface IssueViewController ()<UIScrollViewDelegate,UITextViewDelegate>
{
    float _TimeNUMX;
    float _TimeNUMY;
    int _FontSIZE;
    float allViewHeight;
    //备注文本View高度
    float noteTextHeight;
    int endPage;
    
    int curryPage;
    
    ReleaseResultsView *clearView;
}

@property (nonatomic, strong) UIScrollView *mianScrollView;
@property (nonatomic, strong) BRPlaceholderTextView *noteTextView;


//图片
@property (nonatomic,strong) UIImageView *photoImageView;

@property (nonatomic,strong) UIButton * sureBtn;
@property (nonatomic,strong) NSMutableDictionary * upDic;
@property (nonatomic,strong) NSMutableArray * photoArr;
@property (nonatomic,copy)   NSString * photoStr;
@property (nonatomic,copy)   NSString * star_level;
@property (nonatomic,copy)   NSString * modelUrl;
@property (nonatomic,strong) BRPlaceholderTextView * textField;
@property (nonatomic , strong) NSArray * imageArr;


@end

@implementation IssueViewController


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.labelStr = @"注：最多发布6张图片，第一张为封面";
    [self customNaviItemTitle:@"发布详情" isLeft:YES];
    _TimeNUMX = 1;
    _TimeNUMY = 1.1;
    [self createUI];
    _imageArr =  [[NSArray alloc]init];
    
    
    
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(goToCent:)
                                                 name: @"goToCent"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NotgoToCent:)
                                                 name: @"NotgoToCent"
                                               object:nil];

 
}

/**
 *  取消输入
 */
- (void)viewTapped{
    [self.view endEditing:YES];
}
//#pragma mark 键盘出现
//-(void)keyboardWillShow:(NSNotification *)note
//{
//    self.view.frame = CGRectMake(0, 0-200*_TimeNUMY, ScreenWidth,ScreenHeight);
//}
//#pragma mark 键盘消失
//-(void)keyboardWillHide:(NSNotification *)note
//{
//    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
//}

- (void)createUI{
    _mianScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth , ScreenHeight)];
    _mianScrollView.contentSize =CGSizeMake(ScreenWidth, ScreenHeight);
    _mianScrollView.bounces =YES;
    _mianScrollView.showsVerticalScrollIndicator = false;
    _mianScrollView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_mianScrollView];
    [_mianScrollView setDelegate:self];
    self.showInView = _mianScrollView;
    
    /** 初始化collectionView */
    [self initPickerView];
    
    [self initViews];
    
    
}

/**
 *  初始化视图
 */
- (void)initViews{
    
    
    
    _textField = [[BRPlaceholderTextView alloc] initWithFrame:CGRectMake(10*_TimeNUMX, 10*_TimeNUMY,ScreenWidth - 20, 50*_TimeNUMY)];
    //_textField.placeholder = @"这里输入标题,不超过30个字符";
//    [_textField setValue:RGBA(153, 153, 153, 1) forKeyPath:@"_placeholderLabel.textColor"];
//    [_textField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
     _textField.font = [UIFont systemFontOfSize:15];
    _textField.placeholder = @" 这里输入标题,不超过30个字符";
      [_textField setPlaceholderColor:RGBA(153, 153, 153, 1)];
//    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"这里输入标题,不超过30个字符" attributes:
//                                      @{NSForegroundColorAttributeName:RGBA(153, 153, 153, 1),
//                                        NSFontAttributeName:_textField.font
//                                        }];
//    _textField.attributedPlaceholder = attrString;
//
//    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//    _textField.backgroundColor = [UIColor whiteColor];
//    _textField.layer.cornerRadius = 5;
//    _textField.layer.masksToBounds=YES;
//    _textField.delegate = self;
//    [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    //设置左视图
//    UIView * leftView=[[UIView alloc]initWithFrame:CGRectMake(5, 5, 10, 20)];
//    _textField.leftView=leftView;
//    //左视图显示模式
//    _textField.leftViewMode=UITextFieldViewModeAlways;
//
    
    
    //文本输入框
    _noteTextView = [[BRPlaceholderTextView alloc]init];
    _noteTextView.layer.cornerRadius = 5;
    _noteTextView.layer.masksToBounds=YES;
    _noteTextView.keyboardType = UIKeyboardTypeDefault;
    //文字样式
    
    _noteTextView.maxTextLength = kMaxTextCount;
    [_noteTextView setTextColor:[UIColor blackColor]];
    _noteTextView.delegate = self;
    _noteTextView.font = [UIFont systemFontOfSize:15];
    _noteTextView.placeholder= @" 这里输入文字内容,（1000字以内）";
    [_noteTextView setPlaceholderColor:RGBA(153, 153, 153, 1)];
    
    self.noteTextView.returnKeyType = UIReturnKeyDone;
    [self.noteTextView setPlaceholderColor:[UIColor lightGrayColor]];
    [self.noteTextView setPlaceholderOpacity:1];
    _noteTextView.textContainerInset = UIEdgeInsetsMake(5, 8, 5, 15);
    _noteTextView.font = [UIFont systemFontOfSize:15.0];
    _noteTextView.textColor = [UIColor blackColor];
    
    //确定按钮
    self.sureBtn = [[UIButton alloc] init];
    self.sureBtn.backgroundColor = RGBA(81, 158, 238, 1);
    self.sureBtn.enabled =YES;
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
    [self.sureBtn setTitle: @"发布" forState:UIControlStateNormal];
    [self.sureBtn addTarget:self action:@selector(sureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_mianScrollView addSubview:_textField];
    [_mianScrollView addSubview:_noteTextView];
    
    
    [_mianScrollView addSubview:self.sureBtn];
    
    
    
    [self updateViewsFrame];
    
}



/**
 *  界面布局 frame
 */
- (void)updateViewsFrame{
    
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 100*_TimeNUMY;
    }
    
    
    //文本编辑框
    _noteTextView.frame = CGRectMake(10, _textField.frame.origin.y+_textField.frame.size.height+10*_TimeNUMY, ScreenWidth - 20, noteTextHeight);
    
    
    
    //photoPicker
    [self updatePickerViewFrameY:self.noteTextView.frame.origin.y + self.noteTextView.frame.size.height];
    
    self.sureBtn.frame = CGRectMake(10*_TimeNUMX, [self getPickerViewFrame].origin.y+[self getPickerViewFrame].size.height+30*_TimeNUMY, ScreenWidth-20*_TimeNUMX, 50);
    
    allViewHeight = self.sureBtn.frame.origin.y+self.sureBtn.frame.size.height+10*_TimeNUMY;
    
    _mianScrollView.contentSize = self.mianScrollView.contentSize = CGSizeMake(0,allViewHeight);
}
/**
 *  恢复原始界面布局
 */
-(void)resumeOriginalFrame{
    _textField.frame = CGRectMake(0,80, ScreenWidth, 20);
    //文本编辑框
    _noteTextView.frame = CGRectMake(0, 40*_TimeNUMY, ScreenWidth, noteTextHeight);
    
}

- (void)pickerViewFrameChanged{
    [self updateViewsFrame];
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //当前输入字数
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    [self textChanged];
    return YES;
}

//文本框每次输入文字都会调用  -> 更改文字个数提示框
- (void)textViewDidChangeSelection:(UITextView *)textView{
    //
    
    
    [self textChanged];
}

/**
 *  文本高度自适应
 */
-(void)textChanged{
    
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    
    //获取尺寸
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    
    
    //如果文本框没字了恢复初始尺寸
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }else{
        noteTextHeight = 100;
    }
    
    [self updateViewsFrame];
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.textField) {
        NSInteger kMaxLength = 10;
        NSString *toBeString = textField.text;
        NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage
        if ([lang isEqualToString:@"zh-Hans"]) { //中文输入
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
            if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制
                if (toBeString.length > kMaxLength) {
                    textField.text = [toBeString substringToIndex:kMaxLength];
                }
            }
            else{//有高亮选择的字符串，则暂不对文字进行统计和限制
            }
        }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
            if (toBeString.length > kMaxLength) {
                textField.text = [toBeString substringToIndex:kMaxLength];
            }
        }
    }
}

#pragma mark - UIScrollViewDelegate
//用户向上偏移到顶端取消输入,增强用户体验
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0) {
        [self.view endEditing:YES];
    }
}

-(void)leftButtonEvent:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)sureBtnClicked{
    
    if (_textField.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入标题");
        return;
    }
    if (_noteTextView.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入内容");
        return;
    }
    
    if (self.bigImageArray.count ==0) {
        
        SHuiMBhudTextTimeStr(@"请上传图片");
        return;
    }
    [self upImageAndTitleRequest];
    

//    [self upDataRequest];

}


-(void)upImageAndTitleRequest{
    
    NSLog(@"self.imageArray = %@",self.bigImageArray);
    
    NSMutableArray * img = @[].mutableCopy;
    if (img) {
        [img removeAllObjects];
    }
    for (int i = 0; i<self.bigImageArray.count; i++) {
   
        NSData *data = UIImageJPEGRepresentation(self.bigImageArray[i], 0.5);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
        
        [img addObject:imageStr];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:img
                                                       options:kNilOptions
                                                         error:nil];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    
    NSLog(@" img  = %@  ima.count = %ld",img,img.count);
        NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                               @"token":USER_DEFAULTGet(@"token"),
                               @"mac_code":[SHJudgeTools getDeviceId],
                               @"title":_textField.text,
                               @"content":_noteTextView.text,
                               @"img":jsonString
                               };
    
        NSLog(@"dic = %@",dic);
    
    
     SHuiMBhubNoTimeLoding;
        [PostNetWorking postNetWorkingStr:RequestUrlStr(new_publish_photo_api) andparameters:dic Success:^(id responseObject) {
            SHuiMBHidleYes;
                if (clearView) {

                    [clearView removeFromSuperview];
                }
                clearView = [[ReleaseResultsView alloc]init];
                [clearView initResultsViewWithClear:NO];
                clearView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
                [[UIApplication sharedApplication].keyWindow addSubview:clearView];
        
        } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
            SHuiMBHidleYes;
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode == 404) {
                SHuiMBhudTextTimeStr(@"请稍后再试");
            }else if(responses.statusCode == 403){
                SHuiMBhudTextTimeStr(@"认证失败");
            }else {
                SHuiMBhudTextNetError;
            }
        }];

}


-(void)upDataRequest{

    NSDictionary * dic = @{@"token":USER_DEFAULTGet(@"token"),
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"title":_textField.text,
                           @"content":_noteTextView.text
                           };


    [PostNetWorking postNetWorkingStr:RequestUrlStr(releas_activity_api) andparameters:dic Success:^(id responseObject) {

        NSString * messageId = [NSString stringWithFormat:@"%d",[responseObject[@"id"] intValue]];
        NSLog(@"responseObject = %@",responseObject);

//        for (int i = 0; i<self.bigImageArray.count; i++) {

        
            
//            NSData *data = UIImageJPEGRepresentation(self.imageArray[i], 1);
//            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//            NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
        
            
            
           [self haveImageRequestForId:messageId ];
  

    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {

        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;

        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"认证失败");
        }else {

            SHuiMBhudTextNetError;

        }
    }];

}

 
-(void)haveImageRequestForId:(NSString *)idStr {
    
    endPage = self.bigImageArray.count;
    NSLog(@"self.imageArray = %@",self.imageArray);
    for (int i = 0; i<self.bigImageArray.count; i++) {
           curryPage = i;
        NSData *data = UIImageJPEGRepresentation(self.bigImageArray[i], 0.5);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];

        
        NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                               @"token":USER_DEFAULTGet(@"token"),
                               @"mac_code":[SHJudgeTools getDeviceId],
                               @"uploadType":@"2",
                               @"id":idStr,
                               @"img":imageStr
                               };
        NSLog(@"dic = %@",dic);
        
        [PostNetWorking postNetWorkingStr:RequestUrlStr(releas_image_api) andparameters:dic Success:^(id responseObject) {
            
          if (endPage == curryPage+1) {
            
            if (clearView) {
                
                [clearView removeFromSuperview];
            }
            clearView = [[ReleaseResultsView alloc]init];
            [clearView initResultsViewWithClear:NO];
            clearView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
            [[UIApplication sharedApplication].keyWindow addSubview:clearView];
             }
            
        } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
            
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            
            if (responses.statusCode == 404) {
                SHuiMBhudTextTimeStr(@"请稍后再试");
            }else if(responses.statusCode == 403){
                SHuiMBhudTextTimeStr(@"认证失败");
            }else {
                
            }
        }];
    }
    
   
    
}

-(void)goToCent:(NSNotification *)notification{

    [clearView removeFromSuperview];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"goToCent" object:self];
    MyPictureViewController * pict =[[MyPictureViewController alloc]init];
    pict.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:pict animated:YES];
    
}

-(void)NotgoToCent:(NSNotification *)notification{
    
    [clearView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end



